package org.bigdata.controller;

import org.bigdata.service.HadoopService;
import org.bigdata.service.HiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

//8. 测试和使用
//启动Spring Boot应用后，你可以使用如下接口：
//
//上传文件：
//
//方法：POST
//URL：http://localhost:8080/hadoop/upload
//参数：file（选择需要上传的user.csv文件）
//结果：文件将被上传到HDFS的/user/hadoop/input/目录。
//查询数据：
//
//方法：GET
//URL：http://localhost:8080/hadoop/query
//参数：userId（查询特定用户ID的记录）
//结果：返回查询到的用户信息。

@RestController
@RequestMapping("/hadoop")
public class HadoopController {

    @Autowired
    private HadoopService hadoopService;

    @Autowired
    private HiveService hiveService;

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String hdfsPath = "/user/hadoop/input/" + file.getOriginalFilename();
            hadoopService.uploadFile(file, hdfsPath);
            return "File uploaded successfully to " + hdfsPath;
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload file: " + e.getMessage();
        }
    }

    @GetMapping("/query")
    public String query(@RequestParam String userId) {
        String sql = "SELECT * FROM user_data WHERE userId = '" + userId + "'";
        try {
            ResultSet resultSet = hiveService.query(sql);
            StringBuilder result = new StringBuilder();
            while (resultSet.next()) {
                result.append(resultSet.getString("userId"))
                        .append(", ")
                        .append(resultSet.getString("userName"))
                        .append(", ")
                        .append(resultSet.getString("sex"))
                        .append("\n");
            }
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed to query data: " + e.getMessage();
        }
    }
}

